import { defineComponent, inject, ref, watchEffect, computed, createVNode } from 'vue';
import Icon from '../Icon/index.js';
import Collapase from '../inner/Collapase.js';

const Item = /* @__PURE__ */ defineComponent({
  name: "AccordionItem",
  props: {
    name: {
      type: String
    },
    title: {
      type: [String, Object]
    },
    icon: {
      type: Object
    }
  },
  setup(props, {
    slots
  }) {
    const ctx = inject('CMAccordionContext', null);
    const onSelect = ctx?.onSelect;
    const multi = ctx?.flex ? false : ctx?.multi;
    const opened = ref(false);
    const end = ref(false);
    const onTitleClick = () => {
      let v;
      let open = false;
      if (!multi) {
        if (ctx?.activeKey.value === props.name) {
          if (ctx?.flex) {
            return;
          }
          v = '';
          open = false;
        } else {
          v = props.name;
          open = true;
        }
      } else {
        const currentKey = ctx?.activeKey.value;
        if (currentKey instanceof Array) {
          if (currentKey.includes(props.name)) {
            const index = currentKey.indexOf(props.name);
            currentKey.splice(index, 1);
            v = [].concat(currentKey);
            open = false;
          } else {
            currentKey.push(props.name);
            v = [].concat(currentKey);
            open = true;
          }
        }
      }
      ctx.activeKey.value = v;
      onSelect && onSelect(props.name, open, v);
    };
    watchEffect(() => {
      const currentKey = ctx.activeKey.value;
      let open = false;
      if (!multi) {
        open = currentKey === props.name;
      } else {
        open = currentKey.includes(props.name);
      }
      end.value = false;
      opened.value = open;
    });
    const classList = computed(() => ({
      'cm-accordion-item': true,
      'cm-accordion-item-active': opened.value,
      'cm-accordion-item-full': opened.value && end.value
    }));
    const onEnd = () => {
      end.value = true;
    };
    return () => createVNode("div", {
      "class": classList.value
    }, [createVNode("div", {
      "class": "cm-accordion-title",
      "onClick": onTitleClick
    }, [props.icon, createVNode("div", {
      "class": "cm-accordion-item-title-text"
    }, [props.title]), createVNode(Icon, {
      "class": "cm-accordion-title-arrow",
      "name": "chevron-right"
    }, null)]), createVNode(Collapase, {
      "open": opened.value,
      "onEnd": onEnd
    }, {
      default: () => [createVNode("div", {
        "class": "cm-accordion-content"
      }, [slots.default?.()])]
    })]);
  }
});

export { Item as default };
